package com.eliza.spring.cloud.nacos.provider.service

import com.eliza.spring.cloud.library.mapper.OrderMapper
import com.eliza.spring.cloud.library.pojo.Order
import com.eliza.spring.cloud.library.pojo.User
import com.eliza.spring.library.utils.ToolsLog
import org.mybatis.spring.annotation.MapperScan
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.core.env.Environment
import org.springframework.stereotype.Service
import org.springframework.web.client.RestTemplate
import java.net.Inet4Address
import javax.annotation.Resource


@MapperScan(basePackages = ["com.eliza.spring.cloud.library.mapper"])
@Service
class OrderService {
    @Resource
    private lateinit var environment: Environment

    /*
    * 需要单独新建配置项
    * */
    @Autowired
    private lateinit var restTemplate: RestTemplate

    @Resource
    private lateinit var orderMapper: OrderMapper

    fun queryOrderById(orderId: Long): Order? {
        // 1.查询订单
        // 4.返回
        return orderMapper.findById(orderId)
    }

    fun getAllOrder(): List<Order> {
        return orderMapper.getAllOrder()
    }

    /**
     * Query order and user by order id
     * 使用 restTemplate  从网页返回值获取对象
     * @param orderId
     * @return
     */
    fun queryOrderAndUserByOrderId(orderId: Long): Order? {
        val hostAddress = Inet4Address.getLocalHost().hostAddress//本机访问ip地址
        val port = environment.getProperty("server.port")///开放的 端口
        ToolsLog.LogPrintln("$hostAddress  :$port", 12)

//        从网页返回值获取 对象
//        val url = "http://${hostAddress}:${port}/user/"


        val url = getUrl("nacosConsumer", "user/")
        ToolsLog.LogPrintln("假地址：$url", 13)

        return orderMapper.findById(orderId)?.also { order ->

            ToolsLog.LogPrintln("假地址：$order", 12)

//            2.查询用户
            restTemplate.getForObject(url + order.userId, User::class.java)
                ?.let { user ->
                    ToolsLog.LogPrintln(user)
//                3. 将用户信息封装进订单
                    order.user = user
                }
        }
    }

    /**
     * Get url
     ** 使用Eureka ，通过注册中心，使用 服务名称获取请求地址
     * @param serverName
     * @param path
     */
    private fun getUrl(serverName: String, path: String = "") = "http://${serverName}/${path}"

}